// 防抖函数
export function debounce<F extends (...args: any[]) => any, This>(
  func: F,
  waitFor: number
): (...args: Parameters<F>) => void {
  let timeoutId: NodeJS.Timeout | null = null

  return function (this: This, ...args: Parameters<F>) {
    if (timeoutId !== null) {
      clearTimeout(timeoutId)
    }
    timeoutId = setTimeout(() => {
      func.call(this, ...args)
    }, waitFor)
  }
}

export function throttle<F extends (...args: any[]) => any, This>(
  func: F,
  limit: number
): (this: This, ...args: Parameters<F>) => void {
  let lastFunc: ReturnType<typeof setTimeout>
  let lastRan: number

  return function (this: This, ...args: Parameters<F>) {
    if (!lastRan) {
      func.apply(this, args)
      lastRan = Date.now()
    } else {
      clearTimeout(lastFunc)
      lastFunc = setTimeout(
        () => {
          if (Date.now() - lastRan >= limit) {
            func.apply(this, args)
            lastRan = Date.now()
          }
        },
        limit - (Date.now() - lastRan)
      )
    }
  }
}
